<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>博客详情页</title>

    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/detail.css">
    <link rel="stylesheet" href="css/components.css">

</head>

<body>
<div class="nav">
    <div class="logo-container">
        <div class="logo-icon">B</div>
        <span class="blog-title">我的博客系统</span>
    </div>
    <div class="space"></div>
    <a class="nav-span" href="blog_list.html">主页</a>
    <a class="nav-span" href="blog_edit.html">写博客</a>
    <a class="nav-span" href="#" onclick="logout()">注销</a>
</div>

<div class="container">
    <div class="left">
        <div class="card">
            <img src="pic/doge.jpg" alt="">
            <h3></h3>
            <a href="#">GitHub 地址</a>
            <div class="row">
                <span>文章</span>
                <span>分类</span>
            </div>
            <div class="row">
                <span id="articleCount">0</span>
                <span>1</span>
            </div>
        </div>
    </div>
    <div class="right">
        <div class="content">
            <div class="loading-placeholder" id="contentLoading">
                <div class="loading-spinner"></div>
                <span>加载中...</span>
            </div>
            <div id="contentArea" style="display: none;">
                <div class="title"></div>
                <div class="date"></div>
                <div class="detail" id="detail" style="background: transparent;"></div>
                <div class="operating"></div>
            </div>
        </div>

    </div>
</div>

<!-- 引入 editor.md 的依赖 -->
<link rel="stylesheet" href="blog-editormd/css/editormd.css" />
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    // jQuery 加载失败的备用方案
    if (typeof jQuery === 'undefined') {
        document.write('<script src="blog-editormd/lib/jquery.min.js"><\/script>');
    }
</script>
<script src="blog-editormd/lib/marked.min.js"></script>
<script src="blog-editormd/lib/prettify.min.js"></script>
<script src="blog-editormd/editormd.js"></script>
<script src="js/common.js"></script>
<script>
    // 页面初始化
    $(document).ready(function() {
        getBlogDetail();
        getUserInfo();
    });

    function getUserInfo() {
        const urlParams = new URLSearchParams(location.search);
        const blogId = urlParams.get('blogId');
        if (!blogId) {
            showMessage('博客ID不存在', 'error');
            setTimeout(() => {
                location.href = 'blog_list.html';
            }, 1500);
            return;
        }
        
        const url = "/user/getAuthorInfo" + location.search;
        $.ajax({
            type: "get",
            url: url,
            success: function(result) {
                if (result != null && result.code && result.code.toString() === "SUCCESS" && result.data != null) {
                    const userInfo = result.data;
                    $(".left .card h3").text(userInfo.username || '作者');
                    if (userInfo.githubUrl) {
                        $(".left .card a").attr("href", userInfo.githubUrl).show();
                    } else {
                        $(".left .card a").hide();
                    }
                    
                    // 获取文章数量（可以调用其他API获取）
                    $("#articleCount").text(1); // 这里可以改为实际的文章数量
                } else {
                    console.warn("获取作者信息失败:", result?.errMsg || '未知错误');
                    $(".left .card h3").text('匿名用户');
                    $(".left .card a").hide();
                }
            },
            error: function(xhr, status, error) {
                console.error("获取作者信息失败:", error);
                $(".left .card h3").text('匿名用户');
                $(".left .card a").hide();
            }
        });
    }

    function getBlogDetail() {
        $("#contentLoading").show();
        $("#contentArea").hide();
        
        $.ajax({
            type: "get",
            url: "/blog/getBlogDetail" + location.search,
            success: function(result) {
                $("#contentLoading").hide();
                
                if (result && result.code && result.code.toString() === "FAIL") {
                    showMessage(result.errMsg || '获取博客详情失败', 'error');
                    setTimeout(() => {
                        location.href = 'blog_list.html';
                    }, 2000);
                    return;
                }
                
                if (result && result.code && result.code.toString() === "SUCCESS" && result.data != null) {
                    const blogData = result.data;
                    $("#contentArea").show();
                    
                    // 填充博客内容
                    $(".content .title").text(blogData.title || '无标题');
                    $(".content .date").text(formatDate(blogData.createTime));
                    
                    // 使用 Editor.md 渲染 Markdown
                    try {
                        editormd.markdownToHTML("detail", {
                            markdown: blogData.content || '',
                            htmlDecode: "style,script,iframe",
                            taskList: true,
                            tex: true,
                            flowChart: true,
                            sequenceDiagram: true
                        });
                    } catch (error) {
                        console.error('Markdown渲染失败:', error);
                        $("#detail").html('<p style="color: #666;">' + (blogData.content || '无内容') + '</p>');
                    }

                    // 判断是否显示编辑/删除按钮
                    const loginUserId = localStorage.getItem("loginUserId");
                    if (blogData.userId == loginUserId) {
                        // 当前作者是登录用户，显示按钮
                        const blogId = blogData.id;
                        let finalHtml = '<button class="edit-btn" onclick="editBlog(' + blogId + ')">编辑</button>';
                        finalHtml += '<button class="delete-btn" onclick="deleteBlog(' + blogId + ')">删除</button>';
                        $(".content .operating").html(finalHtml);
                    } else {
                        $(".content .operating").empty();
                    }
                } else {
                    showMessage('获取博客详情失败', 'error');
                    setTimeout(() => {
                        location.href = 'blog_list.html';
                    }, 2000);
                }
            },
            error: function(xhr, status, error) {
                $("#contentLoading").hide();
                showMessage('加载博客详情失败，请刷新页面重试', 'error');
                console.error('获取博客详情失败:', error);
            }
        });
    }

    function editBlog(blogId) {
        window.location.href = 'blog_update.html?blogId=' + blogId;
    }

    function deleteBlog(blogId) {
        showConfirm('确定要删除这篇博客吗？删除后无法恢复。', function() {
            // 显示加载状态
            $(".delete-btn").prop('disabled', true).text('删除中...');
            
            $.ajax({
                type: "post",
                url: "/blog/deleteBlog?blogId=" + blogId,
                success: function(result) {
                    $(".delete-btn").prop('disabled', false).text('删除');
                    
                    if (result && result.code && result.code.toString() === "SUCCESS" && result.data === true) {
                        showMessage('博客删除成功', 'success');
                        setTimeout(() => {
                            location.href = "blog_list.html";
                        }, 1000);
                    } else {
                        showMessage(result.errMsg || '删除失败，请重试', 'error');
                    }
                },
                error: function(xhr, status, error) {
                    $(".delete-btn").prop('disabled', false).text('删除');
                    handleAjaxError(xhr, '删除失败，请重试');
                }
            });
        });
    }
</script>
</body>

</html>